package cn.webdai.controller;

import cn.webdai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 戴金华
 * @date 2019-12-04 22:31
 */
@Controller
public class TestController {

    @Autowired
    private UserService userService;

    @Autowired
    private TemplateEngine templateEngine;

    @RequestMapping("/test")
    public void processTest(){
        //上下文
        Context context = new Context();
        //创建数据模型
        Map<String,Object> dataModel = new HashMap();
        dataModel.put("userList",userService.findAll());

        context.setVariables(dataModel);

        //准备文件
        File file = new File("D:/test/");
        if (!file.exists()){
            file.mkdirs();
        }

        File dest = new File(file, "test.html");
        //生成页面
        try {
            PrintWriter pw = new PrintWriter(dest, "UTF-8");
            //模板解析器
            templateEngine.process("index",context,pw);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
